/*
Author: winter
Date: Oct. 21, 2003
Purpose: log function
*/

#include "uutil.h"

int lprintf(log_t *log, unsigned int level, char *fmt,...) 
{
	int fd, cnt, rc;
  	va_list ap;
  	time_t now;
  	char date[50];
  	static char line[LOGLINE_MAX];
  	
  	static char *levels[6] = { 
  				"[ bad   ] ", 
                             	"[ debug ] ", 
                             	"[ info  ] ", 
                             	"[ warn  ] ", 
                             	"[ error ] ", 
                             	"[ fatal ] " };

	if(!log) return -1;

  	/* If this is debug info, and we're not logging it, return */
  	if( level == DEBUG ) 
  	{
    		fprintf(stdout,"%s\n",fmt);   
    		return 0;
  	}
  	fd=log->fd;
  
  	/* Prepare the date string */
  	if( !(log->flags&LOG_NODATE) ) 
  	{
    		now=time(NULL);
    		strcpy(date,ctime(&now));
    		date[strlen(date)-6]=' ';
    		date[strlen(date)-5]='\0';
  	}
  	cnt = snprintf(line, sizeof(line), "%s%s", date, levels[level]);
  	
  	va_start(ap, fmt);
  	vsnprintf(line+cnt , sizeof(line)-cnt , fmt, ap);
  	va_end(ap);

  	line[sizeof(line)-1] = '\0';   
  	sem_wait(&log->sem);
  	rc = write(fd, line, strlen(line));
  	sem_post(&log->sem);

  	if( !rc ) errno = 0;
  	return rc;
}

log_t *log_open( char *fname, int flags ) 
{
  	log_t *log = malloc(sizeof(log_t));
  
  	if(!log) 
  	{
    		fprintf(stderr, "log_open: Unable to malloc()");
    		return NULL;
  	}
  	log->flags=flags;
  	log->fd = open(fname, O_WRONLY|O_CREAT|O_NOCTTY |  (flags&LOG_TRUNC ? O_TRUNC : O_APPEND) , 0666);         
  	
  	if( log->fd == -1 ) 
  	{
    		fprintf(stderr, "log_open: Opening logfile %s: %s",fname, strerror(errno));
    		free(log); 
  	}
  	if( sem_init(&log->sem, 0, 1) == -1 ) 
 	{
    		fprintf(stderr, "log_open: Could not initialize log semaphore.");
    		close(log->fd);
  	}
  	return log;
}

void log_close( log_t *log ) 
{
	sem_wait(&log->sem);
	sem_destroy(&log->sem);
  	close(log->fd);
  	free(log);
  	return;
}